import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useStore } from '@/stores/index'
// import { useRouter } from 'vue-router'
import router from '@/router'


let url
if (window.location.hostname == '域名') {
  url = ''
} else {
  // url = 'http://localhost:5173'
  url = 'http://101.6.219.33:8080/simulation'
}

export const baseurl = url

const instance = axios.create({
  baseURL: url,
  timeout: 1000,
  // withCredentials: true,
  headers: {
    // 'Access-Control-Allow-Origin': '*',
    // 'Access-Control-Expose-Headers': 'X-Requested-With',
    // 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
    // 'X-Custom-Header': 'foobar'
    // 'Accept': '*/*'
  }
})

instance.interceptors.request.use((config) => {
  const { token } = useStore()
  // if (token) {
  //   config.headers.Authorization = token
  // }
  if (token) {
    config.headers.tgc = token
    // config.headers['Cookie'] = cookie
  }
  return config
})
export async function post(url, params, config) {
  try {
    const res = await instance.post(url, params, config)
    if (res.data.code != 200) {
      let msg = res.data.message;
      if (res.data.code == 401000) {
        router.replace('/login')
        msg = 'token过期，请重新登录';
        console.log('😩', router, msg)
      }
      return ElMessage({
        message: msg,
        grouping: true,
        type: 'error'
      })
    }
    return res
  } catch (err) {
    ElMessage.error('网络错误，请求已超时！')
    return err
  }
}
export async function get(url, params) {
  try {
    const res = await instance.get(url, { params: params })
    if (res.data.code != 200) {
      let msg = res.data.message;
      if (res.data.code == 401000) {
        router.replace('/login')
        msg = 'token过期，请重新登录';
        console.log('😩', router, msg)
      }
      return ElMessage({
        message: msg,
        grouping: true,
        type: 'error'
      })
      // return ElMessage.error(msg)
    }
    return res
  } catch (err) {
    ElMessage.error('网络错误，请求已超时！')
    return err
  }
}
